//
//  file.cpp
//  MyServer
//
//  Created by RJ G on 2025/5/2.
//
#include <iostream>
#include <cstdio>
#include <sys/socket.h>
#include <unistd.h>
#include "file.h"

extern int g_client;

void sendFile(std::string name)
{
    FILE* fp = std::fopen(name.c_str(), "rb");
    if (!fp) {
        std::cout << "文件不存在" << std::endl;
        send(g_client, "\n", 1, 0);
        return;
    }
    fseek(fp, 0, SEEK_END);
    long fileSize = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char buffer[4096];
    long totalSent = 0;
    std::cout << "文件传输中：";
    long partSize = fileSize / 30;
    while (!feof(fp)) {
        size_t len = fread(buffer, sizeof(char), sizeof(buffer), fp);
        send(g_client, buffer, len, 0);
        totalSent += len;
        if (totalSent >= partSize) {
            std::cout << '-';
            partSize += fileSize / 30;
        }
        usleep(20 * 1000);
    }
    fclose(fp);
    std::cout << std::endl << "文件传输完成" << std::endl;
}
